#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简化的RBAC数据迁移脚本
"""

import pymysql
from flask import Flask
from tools.db import init_db
from models.users import AdminUser, Role, Resource, Permission, user_roles, role_permissions, user_resources

def create_database():
    """创建数据库"""
    try:
        connection = pymysql.connect(
            host='localhost',
            user='root',
            password='12345',
            charset='utf8mb4'
        )
        with connection.cursor() as cursor:
            cursor.execute("CREATE DATABASE IF NOT EXISTS management_system CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
        connection.close()
        print("数据库 'management_system' 创建成功")
        return True
    except Exception as e:
        print(f"数据库创建失败: {str(e)}")
        return False

def simple_migrate():
    """简化的数据迁移"""
    try:
        print("开始简化RBAC权限系统数据迁移")
        print("=" * 50)
        
        # 1. 创建数据库
        print("步骤1: 创建MySQL数据库")
        if not create_database():
            return False
        
        # 2. 初始化Flask应用
        print("\n步骤2: 初始化Flask应用")
        app = Flask(__name__)
        db = init_db(app, use_mysql=True)
        print("Flask应用初始化成功")
        
        # 3. 创建所有表
        print("\n步骤3: 创建数据库表")
        with app.app_context():
            db.create_all()
            print("数据库表创建成功")
        
        # 4. 插入基础数据
        print("\n步骤4: 插入基础数据")
        with app.app_context():
            # 清空现有数据
            print("清空现有数据...")
            db.session.query(user_resources).delete()
            db.session.query(role_permissions).delete()
            db.session.query(user_roles).delete()
            db.session.query(AdminUser).delete()
            db.session.query(Permission).delete()
            db.session.query(Resource).delete()
            db.session.query(Role).delete()
            db.session.commit()
            
            # 插入资源数据
            print("插入资源数据...")
            resources_data = [
                (1, '销售管理', 0, 1, 0, '/sales', 'el-icon-sell'),
                (2, '销售订单', 1, 2, 1, '/sales/orders', 'el-icon-document'),
                (3, '销售订单新增', 2, 3, 1, '/sales/orders/add', 'el-icon-plus'),
                (4, '商品管理', 0, 1, 0, '/products', 'el-icon-goods'),
                (5, '新增', 4, 3, 4, '/products/add', 'el-icon-plus'),
            ]
            
            for res_data in resources_data:
                resource = Resource(
                    id=res_data[0],
                    name=res_data[1],
                    pid=res_data[2],
                    level=res_data[3],
                    topid=res_data[4],
                    url=res_data[5],
                    icon=res_data[6]
                )
                db.session.add(resource)
            db.session.flush()
            
            # 插入角色数据
            print("插入角色数据...")
            roles_data = [
                (1, '销售', '销售角色'),
                (2, '商品编辑', '商品编辑角色'),
            ]
            
            for role_data in roles_data:
                role = Role(
                    id=role_data[0],
                    name=role_data[1],
                    description=role_data[2]
                )
                db.session.add(role)
            db.session.flush()
            
            # 插入权限数据
            print("插入权限数据...")
            permissions_data = [
                (1, '销售订单新增权限', 3, 'write'),
                (2, '商品新增权限', 5, 'write'),
            ]
            
            for perm_data in permissions_data:
                permission = Permission(
                    id=perm_data[0],
                    name=perm_data[1],
                    resource_id=perm_data[2],
                    action=perm_data[3]
                )
                db.session.add(permission)
            db.session.flush()
            
            # 插入用户数据
            print("插入用户数据...")
            users_data = [
                (1, 'zs', '12344400001', 1),
                (2, 'zs1', '12344400002', 1),
                (3, 'xm', '12344400003', 2),
            ]
            
            for user_data in users_data:
                user = AdminUser(
                    id=user_data[0],
                    name=user_data[1],
                    mobile=user_data[2],
                    roleid=user_data[3]
                )
                db.session.add(user)
            db.session.flush()
            
            # 建立角色权限关系
            print("建立角色权限关系...")
            # 销售角色 -> 销售订单新增权限
            sales_role = Role.query.get(1)
            sales_permission = Permission.query.get(1)
            sales_role.permissions.append(sales_permission)
            
            # 商品编辑角色 -> 商品新增权限
            product_role = Role.query.get(2)
            product_permission = Permission.query.get(2)
            product_role.permissions.append(product_permission)
            
            # 建立用户资源关系
            print("建立用户资源关系...")
            # 用户zs -> 销售订单新增资源
            user_zs = AdminUser.query.get(1)
            sales_order_add_resource = Resource.query.get(3)
            user_zs.resources.append(sales_order_add_resource)
            
            # 用户zs -> 商品新增资源
            product_add_resource = Resource.query.get(5)
            user_zs.resources.append(product_add_resource)
            
            db.session.commit()
            print("基础数据初始化成功")
        
        print("\nRBAC权限系统数据迁移完成！")
        print("数据统计:")
        
        with app.app_context():
            user_count = AdminUser.query.count()
            role_count = Role.query.count()
            resource_count = Resource.query.count()
            permission_count = Permission.query.count()
            
            print(f"  用户数量: {user_count}")
            print(f"  角色数量: {role_count}")
            print(f"  资源数量: {resource_count}")
            print(f"  权限数量: {permission_count}")
        
        return True
        
    except Exception as e:
        print(f"迁移失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    success = simple_migrate()
    if success:
        print("\n数据迁移完成，可以启动应用:")
        print("   python app_with_redis.py")
    else:
        print("\n数据迁移失败")
        exit(1)
